package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1、根据code换取accessToken
        Map<String,String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("client_id","d69cff5ea203d042470799a0941cc82214739055379bebf60c01178d5cdad2c0");
        map.put("client_secret","d29640403f2acc9290a5ba4d941cd657949498d7c9f4229b4221f71babff9037");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map,new HashMap<>());
        //2、登录成功就跳回首页
        if (response.getStatusLine().getStatusCode() == 200){

            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R oauthlogin = memberFeignService.oauthLogin(socialUser);
            if (oauthlogin.getCode() == 0){
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功：用户{}",data);
                //TODO 1、默认发的令牌。 session=asdfg。 作用域：当前作用域；（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象数据到redis中；
                session.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
        return "redirect:http://gulimall.com";

    }
}
